package com.hibernate.hrm.entity.dto.contract;

import com.hibernate.hrm.entity.Contract;
import com.hibernate.hrm.entity.Department;
import com.hibernate.hrm.entity.User;
import lombok.Data;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

@Data
public class ContractDTO {
    private Integer contractId;
    private String contractNumber;
    private String contractName;
    private Contract.ContractType contractType;
    private User signingPartyA;
    private User signingPartyB;
    private LocalDate effectiveDate;
    private LocalDate expiryDate;
    private Contract.ContractStatus status;
    private Department department;
    private Boolean isOverdue;
    private Long overdueDays;
    private BigDecimal penaltyAmount;
    private BigDecimal penaltyRate;

    public static ContractDTO fromEntity(Contract contract) {
        ContractDTO dto = new ContractDTO();
        dto.setContractId(contract.getContractId());
        dto.setContractNumber(contract.getContractNumber());
        dto.setContractName(contract.getContractName());
        dto.setContractType(contract.getContractType());
        dto.setSigningPartyA(contract.getSigningPartyA());
        dto.setSigningPartyB(contract.getSigningPartyB());
        dto.setEffectiveDate(contract.getEffectiveDate());
        dto.setExpiryDate(contract.getExpiryDate());
        dto.setStatus(contract.getStatus());
        dto.setDepartment(contract.getDepartment());
        dto.setPenaltyRate(contract.getPenaltyRate());

        // 设置状态
        dto.setStatus(contract.getStatus());

        // 计算逾期状态
        LocalDate today = LocalDate.now();
        boolean isOverdue = contract.getStatus() == Contract.ContractStatus.逾期 ||
                (contract.getExpiryDate() != null &&
                        contract.getExpiryDate().isBefore(today));

        dto.setIsOverdue(isOverdue);

        if (isOverdue && contract.getExpiryDate() != null) {
            dto.setOverdueDays(ChronoUnit.DAYS.between(contract.getExpiryDate(), today));
            dto.setPenaltyAmount(contract.getPenaltyRate() != null ?
                    contract.getPenaltyRate().multiply(new BigDecimal(dto.getOverdueDays())) :
                    BigDecimal.ZERO);
        } else {
            dto.setOverdueDays(0L);
            dto.setPenaltyAmount(BigDecimal.ZERO);
        }

        return dto;
    }
}
